package com.gosophia.ajax.proxy.action;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.gosophia.util.TimeName;
import com.gosophia.util.cache.Cache;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 请求代理
 * @author 尹航
 *
 */
@Controller("RequestProxyAction")
@Scope("prototype")
public class RequestProxyAction extends ActionSupport {
    
    private static final long serialVersionUID = 1L;
    private static final Pattern CHARSET_REGEXP = Pattern.compile("charset=.*");
    private String uri;
    private String charset;
    private String resultData;
    
    @Override
    public String execute() throws Exception {
    	if(uri == null || uri.length() <= 0)
    		return SUCCESS;
    	//取缓存
    	resultData = (String) Cache.GETDATA(uri);
    	if(resultData != null)
    		return SUCCESS;
    	URI	targetUri = new URI(uri);
    	if(targetUri.isAbsolute() == false)
    		return SUCCESS;
    	URL targetUrl = targetUri.toURL();
    	HttpURLConnection conn = (HttpURLConnection) targetUrl.openConnection();
    	conn.setRequestMethod("GET");  
    	conn.setDoInput(true);
    	if(charset == null || charset.length() <= 0)
    	{
	    	String contentType = conn.getHeaderField("Content-Type");
	    	charset = "utf-8";
	    	if(contentType != null)
	    	{
	    		Matcher matcher = CHARSET_REGEXP.matcher(contentType);
	    		if(matcher.find())
	    			charset = matcher.group().split(";")[0].split("=")[1];
	    	}
    	}
    	BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream(), charset));
    	String line;
    	StringBuffer sb = new StringBuffer();
    	while((line = br.readLine()) != null)
    	{
    		sb.append(line);
    	}
    	resultData = sb.toString();
    	br.close();
    	conn.disconnect();
    	Cache.SAVE(uri, resultData, TimeName.DAY / 2);
        return SUCCESS;
    }

	public void setUri(String uri) {
		this.uri = uri;
	}

	public String getResultData() {
		return resultData;
	}

	public void setCharset(String charset) {
		this.charset = charset;
	}
}
